package com.techsen.maven.plugins.util;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class XmlHelper {

    private Document document;

    public XmlHelper(File file) {
        try{
            this.document = new SAXReader().read(file);
        } catch (DocumentException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
    
    public XmlHelper write(File file) {
        XMLWriter xmlWriter = null;
        try {
            xmlWriter = new XMLWriter(new FileWriter(file));
            xmlWriter.write(this.document);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            if (xmlWriter != null) {
                try {
                    xmlWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return this;
    }
    
    /**
     * if xml document has namespace then set xpath namespace uri,<br/>
     * if namespace has prefix then set prefix, otherwise set root element tagname
     */
    public XPath createXpath(String xpath) {
        XPath x = this.document.createXPath(xpath);
        
        Element root = this.document.getRootElement();
        if (!"".equals(root.getNamespaceURI())) {
            Map<String, String> map = new HashMap<String, String>();
            
            String prefix = root.getNamespacePrefix();
            prefix = "".equals(prefix) ? root.getName() : prefix;
            
            map.put(prefix, root.getNamespaceURI());
            x.setNamespaceURIs(map);
        }

        return x;
    }
    
    public Document getDocument() {
        return document;
    }

    public XmlHelper setDocument(Document document) {
        this.document = document;
        return this;
    }
    
}
